package com.hongyun.tms.infra;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import java.util.Collection;

/**
 * <p>jsr-303不支持controller层集合参数的校验，此类实现此功能，只要在集合前面加上 @Valid即可验证List的参数</p>
 */
public class CollectionValidator implements Validator {

    private final LocalValidatorFactoryBean validator;

    public CollectionValidator(LocalValidatorFactoryBean validator) {
        this.validator = validator;
    }


    @Override
    public boolean supports(Class<?> clazz) {
        return Collection.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Collection collection = (Collection) target;
        if (CollectionUtils.isNotEmpty(collection)) {
            for (Object object : collection) {
                ValidationUtils.invokeValidator(validator, object, errors);
            }
        }
    }
}
